<?php

function __autoload($nome) {
  require_once $nome . ".php";
}

function adjustMoney($money) {
  if($money !== null) {
    bcscale(2);
    return "R$" . str_replace(".",",",bcadd($money,"0"));
  }
  else {
    return null;
  }
}

define("LOG_DIR", "log");
define("LOGGING_PREFIX", "./log/log_");
define("LOGGING_SUFFIX", ".txt");

function logMessage($message, $descWord = "") {
  if(!is_dir(LOG_DIR) && !file_exists(LOG_DIR)) {
    mkdir(LOG_DIR);
  }
  $name = LOGGING_PREFIX . strval(microtime(true)) . "_" . $descWord . LOGGING_SUFFIX;
  @file_put_contents($name, var_export($message, true));
}

class InvalidSessionLoggedAsException extends Exception {
  public function __construct($message = "", $code = 0, $previous = null) {
    parent::__construct($message, $code, $previous);
  }
}

class EmptySessionLoginNameException extends Exception {
  public function __construct($message = "", $code = 0, $previous = null) {
    parent::__construct($message, $code, $previous);
  }
}

class SessionLoginIsNotStringException extends Exception {
  public function __construct($message = "", $code = 0, $previous = null) {
    parent::__construct($message, $code, $previous);
  }
}

class SessionLoginIsNotIntegerException extends Exception {
  public function __construct($message = "", $code = 0, $previous = null) {
    parent::__construct($message, $code, $previous);
  }
}

class NotLoggedInException extends Exception {
  public function __construct($message = "", $code = 0, $previous = null) {
    parent::__construct($message, $code, $previous);
  }
}

class InvalidLoginGivenException extends Exception {
  public function __construct($message = "", $code = 0, $previous = null) {
    parent::__construct($message, $code, $previous);
  }
}

# Chave/Valor para o formulário que lida com fazer uma reserva.
define("ESTAGIO_RESERVA", "ESTAGIO_RESERVA");
define("PREENCHEU_NADA", 1);
define("PREENCHENDO_DATAFILIAL", 2);
define("PREENCHEU_DATAFILIAL", 3);
define("PREENCHENDO_MODELO", 4);
define("PREENCHEU_MODELO", 5);
define("FILIAL_OBTENCAO", "FILIAL_OBTENCAO");
define("FILIAL_DEVOLUCAO", "FILIAL_DEVOLUCAO");
define("FILIAL_OBTENCAO_NOME", "FILIAL_OBTENCAO_NOME");
define("FILIAL_DEVOLUCAO_NOME", "FILIAL_DEVOLUCAO_NOME");
define("DATA_PREV_INICIO", "DATA_PREV_INICIO");
define("DATA_PREV_FIM", "DATA_PREV_FIM");

function clearReservationSession() {
  unset($_SESSION[ESTAGIO_RESERVA]);
  unset($_SESSION[FILIAL_OBTENCAO]);
  unset($_SESSION[FILIAL_DEVOLUCAO]);
  unset($_SESSION[FILIAL_OBTENCAO_NOME]);
  unset($_SESSION[FILIAL_DEVOLUCAO_NOME]);
  unset($_SESSION[DATA_PREV_INICIO]);
  unset($_SESSION[DATA_PREV_FIM]);
}


# Chaves e valores para o array $_SESSION que dizem respeito ao login do usuário. Eles devem estar setados caso o 
# usuário esteja logado, e não setados caso o usuário não esteja.
define("SESSION_LOGGED_AS", "loggedas"); # Logado como cliente (LOGGED_CLIENT), funcionário (LOGGED_EMPLOYEE) ou 
                                         # admin (LOGGED_ADMIN)?
define("SESSION_LOGIN", "login"); # Qual o id do usuário?

# Possívels valores para $_SESSION[SESSION_LOGGED_AS].
define("LOGGED_CLIENT", "client");
define("LOGGED_EMPLOYEE", "employee");
define("LOGGED_ADMIN", "admin");

function logout() {
  unset($_SESSION[SESSION_LOGGED_AS]);
  unset($_SESSION[SESSION_LOGIN]);
  unset($_SESSION["FILIAL_OBTENCAO"]);
  unset($_SESSION["FILIAL_DEVOLUCAO"]);
  unset($_SESSION["DATA_PREV_INICIO"]);
  unset($_SESSION["DATA_PREV_FIM"]);
}

function gotoIndex() {
  header("Location: index.php");
}

function isLoggedIn() {
  return isset($_SESSION[SESSION_LOGGED_AS]) && isset($_SESSION[SESSION_LOGIN]);
}

function isLoggedAsClient($login = null) {
  $logged = isLoggedIn();
  if($logged && $login === null) {
    return $_SESSION[SESSION_LOGGED_AS] == LOGGED_CLIENT;
  }
  else if(!$logged) {
    return false;
  }
  else {
    $loginType = gettype($login);
    if($loginType === "string") {
      if(preg_match("%^[0-9]+$%", $login) === 1) {
        $login = intval($login);
      }
      else {
        throw new InvalidLoginGivenException(serialize($login));
      }
    }
    else if($loginType != "integer") {
      throw new InvalidLoginGivenException(serialize($login));
    }
    return $_SESSION[SESSION_LOGGED_AS] == LOGGED_CLIENT && $_SESSION[SESSION_LOGIN] === $login;
  }
}

function isLoggedAsAdmin() {
  return isLoggedIn() && $_SESSION[SESSION_LOGGED_AS] == LOGGED_ADMIN;
}

function isLoggedAsEmployee() {
  return isLoggedIn() && $_SESSION[SESSION_LOGGED_AS] == LOGGED_EMPLOYEE;
}

function isActiveUser() {
  $db = new DBUtils();
  try {
    if(isLoggedAsClient()) {
      $table = "cliente";
      $idAttr = "idCliente";
    }
    else if(isLoggedAsAdmin()) {
      $table = "matriz";
      $idAttr = "idMatriz";
    }
    else if(isLoggedAsEmployee()) {
      $table = "filial";
      $idAttr = "idFilial";
    }
    else {
      return true;
    }
    $db->connect();
    $db->runQuery("select * from ${table} where ${idAttr} = ? and ativo = 1", array(intval(userId())));
    $item = $db->getItem();
    $db->close();
    if($item !== null) {
      return true;
    }
  }
  catch(DBError $e) {
    logMessage($e->errors, "isActiveUser");
  }
  logout();
  return false;
}

function mustBe($cond) {
  if(!$cond) {
    gotoIndex();
  }
}

function mustBeLoggedIn() {
  mustBe(isLoggedIn());
}

function mustBeClient($login = null) {
  mustBe(isLoggedAsClient($login));
}

function mustBeEmployee() {
  mustBe(isLoggedAsEmployee());
}

function mustBeAdmin() {
  mustBe(isLoggedAsAdmin());
}

function mustBeActive() {
  mustBe(isActiveUser());
}

function userId() {
  if(isLoggedIn()) {
    return $_SESSION[SESSION_LOGIN];
  }
  else {
    throw new NotLoggedInException("Pedindo pelo id name estando deslogado.");
  }
}

function correctStdFormGET() {
  if(!isset($_GET[StdForm::ACTION_KEY])) {
    $_GET[StdForm::ACTION_KEY] = StdForm::ACTION_VALUE_PRINT;
  }
}

function confirm($question, $yesText, $yesLink, $noText, $noLink) {
  $html = <<<HTML
<p class='confQuestion'>${question}</p>
<ul class='conf'>
<li><a href='${yesLink}'>${yesText}</a></li>
<li><a href='${noLink}'>${noText}</a></li>
</ul>
HTML;
  return $html;
}

session_start();

if(isset($_SESSION[SESSION_LOGGED_AS]) &&
        $_SESSION[SESSION_LOGGED_AS] !== LOGGED_ADMIN &&
        $_SESSION[SESSION_LOGGED_AS] !== LOGGED_CLIENT &&
        $_SESSION[SESSION_LOGGED_AS] !== LOGGED_EMPLOYEE) {
  throw new InvalidSessionLoggedAsException($_SESSION[SESSION_LOGGED_AS]);
}
else if(isset($_SESSION[SESSION_LOGIN])) {
  if(gettype($_SESSION[SESSION_LOGIN]) !== "integer") {
    throw new SessionLoginIsNotIntegerExeption($_SESSION[SESSION_LOGGED_AS] . "-" . gettype($_SESSION[SESSION_LOGIN]));
  }
}


mustBeActive();
